发布JSON数据并在android中接收响应

时间:2016-03-05 22:13:20

标签: android json post httpurlconnection

我想将简单的JSON发布到网络服务并接收回复,但我在java.io.IOException : No authentication challenges found上收到client.getResponseCode()错误

我试过this solution,但它对我不起作用。

这是我的代码:

StringBuilder sb = new StringBuilder();
HttpURLConnection client = null;

try {
     URL url = new URL("http://myurl:3000");
     client = (HttpURLConnection) url.openConnection();
     client.setDoOutput(true);
     client.setDoInput(true);
     client.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
     client.setRequestProperty("Authorization", "Basic " + Base64.encodeToString("userid:pwd".getBytes(), Base64.NO_WRAP));
     client.setRequestMethod("POST");

     client.connect();

     OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());
     String output = json.toString();
     writer.write(output);
     writer.flush();
     writer.close();

     int HttpResult = client.getResponseCode();
     if (HttpResult == HttpURLConnection.HTTP_OK) {
         BufferedReader br = new BufferedReader(new InputStreamReader(
                            client.getInputStream(), "utf-8"));
         String line = null;
         while ((line = br.readLine()) != null) {
               sb.append(line + "\n");
         }
         br.close();
     }
} catch (IOException e) {
  this.e = e;
} finally {
  client.disconnect();
}

3 个答案:

答案 0 :(得分:1)

尝试此示例来编码用户名密码

JsonArrayRequest loadMoreRequest = new JsonArrayRequest(url,new Response.Listener<JSONArray>()
{
    @Override
    public void onResponse(JSONArray response)
    {
        try
        {
            for (int i = 0; i < response.length(); i++)
            {
                JSONObject obj = response.getJSONObject(i);
                //Some Logic
            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
    }
},
new Response.ErrorListener()
{
    @Override
    public void onErrorResponse(VolleyError error)
    {
        Toast.makeText(getActivity(), error.toString(),Toast.LENGTH_LONG).show();
    }
});
requestQueue.add(loadMoreRequest);

答案 1 :(得分:0)

如果你尝试使用由Square开发者制作的Android的HTTP客户端OkHttp,我认为你会取得更大的成功。它增加了一层抽象,因此您不必为简单的POST请求编写如此多的代码。以下是POST请求到服务器的代码示例:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

(我会将此添加为评论,但我还没有SO代表)

答案 2 :(得分:0)

您确定服务器网站上有有效的Android令牌吗?这只是一个随意的想法,但我前段时间遇到了类似的问题;)