我正在后端构建一个带有关联REST API的webapp。
使用django-rest-framework创建的API工作正常,我可以从命令行执行以下操作:
$ http http://localhost:8000/API/api-token-auth/ username=ortho1 password=123456
HTTP/1.0 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Date: Wed, 11 May 2016 12:43:05 GMT
Server: WSGIServer/0.2 CPython/3.5.1+
Vary: Cookie
X-Frame-Options: SAMEORIGIN
{
"token": "4d6e32726e321448fc212242fc03a3fa84c80510"
}
但是从我的Android应用程序中我尝试执行以下操作:
protected String doInBackground(String... urls) {
// Starting the request
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://10.0.2.2:8000/API/api-token-auth/");
urlConnection = (HttpURLConnection) url.openConnection();
/* optional request header */
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
/* for GET request */
urlConnection.setRequestMethod("POST");
String urlParameters =
"username=" + URLEncoder.encode("ortho1", "UTF-8") +
"&password=" + URLEncoder.encode("123456", "UTF-8");
urlConnection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
DataOutputStream wr = new DataOutputStream (
urlConnection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
InputStream inputStream;
if (urlConnection.getResponseCode() == 200) { // 2xx code means success
inputStream = urlConnection.getInputStream();
} else {
inputStream = urlConnection.getErrorStream();
}
inputStream = new BufferedInputStream(inputStream);
String response = convertInputStreamToString(inputStream);
Log.i("Request", response);
return response;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(urlConnection != null) {
urlConnection.disconnect();
}
}
}
private String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null){
result += line;
}
/* Close Stream */
if(null!=inputStream){
inputStream.close();
}
return result;
}
我作为来自服务器的响应进入控制台:
{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}
结果。
我可能做错了什么?
答案 0 :(得分:2)
尝试删除此行,
urlConnection.setRequestProperty(“Content-Type”,“application / json”);
对于您的信息,处理任何 REST API 的最佳库是 RETROFIT http://square.github.io/retrofit/
答案 1 :(得分:0)
(狂野猜测)
我看到您的服务器在localhost中运行,并且您正在尝试使用无法正常工作的IP来访问它。如果您在本地测试,请尝试在广播IP中运行服务器:
$ python manage.py runserver 0.0.0.0:8000
或者如果您需要公共地址,您可以使用ngrok
之类的服务将您的请求路由到本地服务器
答案 2 :(得分:0)
urlConnection.setRequestProperty("Content-Type", "application/json");.
你在控制台命令中的哪个位置说明必须发送json? django期待json吗? Django发送json是的。更改为表单url编码而不是