![](/img/trans.png)
[英]Android koush/ion lib unable to post and receive JSON response
[英]Post JSON data and receive response in android
我想将简单的JSON发布到Web服务并接收响应,但是我正在获取java.io.IOException : No authentication challenges found
client.getResponseCode()
上client.getResponseCode()
java.io.IOException : No authentication challenges found
错误
我尝试了此解决方案,但对我不起作用。
这是我的代码:
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();
}
试试这个例子来编码用户名密码
username = mUsername.getText().toString();
password = mPassword.getText().toString();
mResult.setText(username + ":" + password);
mCombination = username + ":" + password;
byte[] byteArray = new byte[0];
try {
byteArray = mCombination.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
final String base64 = Base64.encodeToString(byteArray, Base64.NO_WRAP);
mEncoded.setText(base64);
我认为,如果尝试使用由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代表)
您确定服务器站点上有有效的android令牌吗? 这只是一个随机的想法,但前一段时间我也遇到过类似的问题;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.