问题
I am currently working on a project in which I need to send username,password and email of a user for registering the user on my server. I used POST command for that and as I have to send 3 values for register a user,I used ContentValues for that purpose. Here is my code:
@Override
protected String doInBackground(String... params) {
try {
url = new URL(params[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
ContentValues values = new ContentValues();
values.put("email", "abc@xyz.com");
values.put("password", "123");
values.put("name","ABC");
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(getQuery(values));
bufferedWriter.flush();
statusCode = httpURLConnection.getResponseCode();
Log.i("Result",String.valueOf(statusCode));
inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = inputStreamReader.read();
}
JSONObject jsonObject = new JSONObject(result);
Log.i("Result",String.valueOf(jsonObject));
if (statusCode == 200) {
inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
Log.i("Result","Correct Data Returned");
JSONObject jsonObject = new JSONObject(response);
return true;
} else {
Log.i("Result","Data not returned");
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
Here is my getQuery method:
private String getQuery(ContentValues values) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, Object> entry : values.valueSet())
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
}
Log.i("Result",result.toString());
return result.toString();
}
But I am getting following response by it:
Result: name=ABC&email=abc%40xyz.com&password=123
Result: 422
System.err: java.io.FileNotFoundException: http://docpanel.myworkdetails.com/api/auth/register
Where 422 is the status code returned by responseCode that means :
"errors": {
"email": [
"The email field is required."
],
"password": [
"The password field is required."
],
"name": [
"The password field is required."
]
},
"status_code": 422
I am not getting how to pass arguements by POST method so as to make my signup page working. And I have the correct URL.
Is this server side fault or I am making mistakes in implementing POST?
Please Help! Thanks in advance.
回答1:
Why don't you just concatenate the url with the parameters?
The request would then look like this: "http://example.com/test?param1=a¶m2=b¶m3=c"
回答2:
You could use HttpPost instead of HttpURLConnection
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, Constants.CONNECTION_TIMEOUT);
HttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost("yourBackendUrl");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("key","value"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
InputStream inStream = response.getEntity().getContent();
builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject json = new JSONObject(builder.toString());
回答3:
Solved
I was making mistakes that I didn't add httpUrlConnection.connect() at right place and also httpURLConnection.setRequestProperty("Accept","/") at right place made it working fine. So here is the correct code by which POST request using HttpUrlConnection is used to make signUp page possible:
protected String doInBackground(String... params) {
try {
url = new URL(params[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept","*/*");
ContentValues values = new ContentValues();
values.put("email", "abc@tjk.com");
values.put("password", "hjh");
values.put("name","hui");
httpURLConnection.connect();
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(getQuery(values));
bufferedWriter.flush();
statusCode = httpURLConnection.getResponseCode();
inputStream = httpURLConnection.getInputStream();
if (statusCode == 200) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = inputStreamReader.read();
}
JSONObject jsonObject = new JSONObject(result);
Log.i("Result",String.valueOf(jsonObject));
} else {
Log.i("Result","false");
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
来源:https://stackoverflow.com/questions/38013669/post-request-for-registering-user-data-on-server-by-httpurlconnection