【问题标题】:Https PUT request with user name and password which send the JSON file as a payload带有用户名和密码的 Https PUT 请求,将 JSON 文件作为有效负载发送
【发布时间】:2015-05-12 09:23:23
【问题描述】:

我是 Java 新手。我有一个 URL、用户名、密码。我需要使用 URL、用户名和密码发出 PUT HTTP 请求。 我必须使用 HTTP Put 请求将 JSON 文件作为有效负载发送到只能接受 JSON 的系统。

我在 StackOverFlow 中进行了搜索,发现很少有可以在没有用户名和密码的情况下对 URL 进行简单请求的建议。但是我们的 URL 需要经过身份验证才能发出请求。

我用来发出 HTTP 请求的代码

public static void main (String args[]) throws IOException
 {
  String userPassword = "";
  String encoding = new String(Base64.encodeBase64(userPassword.getBytes()));
  URL url = new URL(URL);
  HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
  httpCon.setDoOutput(true);
  httpCon.setRequestMethod("PUT");
  httpCon.setRequestProperty("Authorization", "Basic "+encoding);
  OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
  out.write("Resource content");
  out.close();
  httpCon.getInputStream();
 }

【问题讨论】:

  • 那么您的问题到底是什么?什么不起作用,身份验证?您收到错误消息吗?
  • 我在线程“main”java.net.ConnectException中收到以下错误异常:连接被拒绝:在java.net.DualStackPlainSocketImpl.connect0(本机方法)处连接
  • 我需要帮助我发出 HTTP 请求并可能帮助我通过 Http 请求将 JSON 数据发送到 URL 的 java 代码。

标签: java json http httprequest


【解决方案1】:

使用 volley 库..很容易

    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "<your url>";

    JSONObject jsonrequest=new JSONObject();
    jsonrequest.put("username",<username>);
    jsonrequest.put("password",<password>);

    JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, jsonrequest, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            // TODO Auto-generated method stub
            //your code to handle when response came
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            // TODO Auto-generated method stub

        }
    });

    queue.add(jsObjRequest);

【讨论】:

  • 你能帮我下载 volley 库吗?
  • 您使用的是哪个 IDE?
  • Android Studio 还是 Eclipse?
猜你喜欢
  • 1970-01-01
  • 2019-11-14
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
相关资源
最近更新 更多