Can anyone give me a HTTP PUT request example code for Android?
Assuming you want to use an HttpURLConnection, to perform an HTTP PUT you use the following:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Data you want to put");
out.close();
To use the HTTPPut class then try:
URL url = new URL("http://www.example.com/resource");
HttpClient client = new DefaultHttpClient();
HttpPut put= new HttpPut(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("key1", "value1"));
pairs.add(new BasicNameValuePair("key2", "value2"));
put.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(put);
I'm pretty sure this should work though I haven't tested it :)
It's better to use a library like Android Async HTTP or Volley that take the complexity out of networking and make it easier to handle request responses. This is how you would do it with AsyncHTTP:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("some_key", "value-1");
params.put("another_key", "value-2");
client.put(url, params, new AsyncHttpResponseHandler {
public void onSuccess(int statusCode, Header[] headers, String response) {
// Do something with response
}
});
Related
The AsyncHttpClient version is 1.4.7.
The server recieves the request, but could not find the file param
Working example
HttpClient httpclient;
HttpPost httppost;
httpclient = new DefaultHttpClient();
httppost = new HttpPost(URLRepo.URL_IMAGESAVE);
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user_id", ""+deichapp.getInt("userid", 0)));
//.. add parameters
File file = new File(new URI(obj.getString("fileUri")));
nameValuePairs.add(new BasicNameValuePair("filename", file.getName()));
httpclient.getParams().setParameter("Connection", "Keep-Alive");
httpclient.getParams().setParameter("Content-Type", "multipart/form-data;");
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
for (BasicNameValuePair nameValuePair : nameValuePairs) {
entity.addTextBody(nameValuePair.getName(), nameValuePair.getValue());
}
entity.addPart("file", new FileBody(new File(new URI(obj.getString("fileUri")))));
httppost.setEntity(entity.build());
// Send and store the Image
HttpResponse response = httpclient.execute(httppost);
String json;
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
json = reader.readLine();
This uses the native android api and no external librarys like async http client. Make sure you execute this code on a background thread.
Try this:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("notes", "Test api support");
client.post(restApiUrl, params, responseHandler);
Hope this helps!
I'm working on a project which requires me to send a post request to
http://sagecell.sagemath.org/kernel (just a post, no data)along with two extra headers,
Accept-Encoding:identity and accepted_tos:true.
This works fine if using the default httpClient like so:
httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost();
String url = UrlUtils.getKernelURL();
httpPost.setURI(URI.create(url));
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair(HEADER_ACCEPT_ENCODING,VALUE_IDENTITY));
postParameters.add(new BasicNameValuePair(HEADER_TOS,"true"));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
webSocketResponse = gson.fromJson(new InputStreamReader(inputStream), WebSocketResponse.class);
inputStream.close();
However if I want to use the same thing using the OkHttpClient, it gives me a 403 error:
httpClient = new OkHttpClient();
public static final MediaType jsonMediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonMediaType, "");
Request request = new Request.Builder()
.addHeader(HEADER_ACCEPT_ENCODING, VALUE_IDENTITY)
.addHeader(HEADER_TOS, "true")
.url(url)
.post(body) //I've tried null here as well
.build();
Response response = httpClient.newCall(request).execute();
Log.i(TAG,"STATUS CODE"+response.code()); //This is 403
This is the same story with libraries like Ion and even HttpUrlConnection, only the Apache Client seems to work.
Any answers as to why this isn't working would be appreciated.
error 403 means its forbidden by the server.
And in the first case(while using default httpclient ) you are not adding header, you are just adding a name-value pair to the entity.
to add a header you should use
httpPost.addHeader("key","value");
Your request body is empty. You should provide a form-encoded request body, or a JSON request body, and the corresponding content type.
If you want, MimeCraft will build you a form-encoded request body, and Gson will do JSON.
I am doing an Android application and I have a problem doing my request against my own server. I have made the server with Play Framework, and I get the parameters from a Json:
response.setContentTypeIfNotSet("application/json; charset=utf-8");
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(getBody(request.body));
Long id =jsonElement.getAsJsonObject().get("id").getAsLong();
When I make my GET request against my server, all is ok. But when I make a POST request, my server return me an unknown error, something about there is a malformed JSON or that it is unable to find the element.
private ArrayList NameValuePair> params;
private ArrayList NameValuePair> headers;
...
case POST:
HttpPost postRequest = new HttpPost(host);
// Add headers
for(NameValuePair h : headers)
{
postRequest.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty())
{
postRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(postRequest, host);
break;
I have tried to do with the params of the request, but it was a failure:
if(!params.isEmpty())
{
HttpParams HttpParams = new BasicHttpParams();
for (NameValuePair param : params)
{
HttpParams.setParameter(param.getName(), param.getValue());
}
postRequest.setParams(HttpParams); }
And there is the different errors, depends on the request I make. All of them are 'play.exceptions.JavaExecutionException':
'com.google.gson.stream.MalformedJsonException'
'This is not a JSON Object'
'Expecting object found: "id"'
I wish somebody can help me.
Here is a simple way to send a HTTP Post.
HttpPost httppost = new HttpPost("Your URL here");
httppost.setEntity(new StringEntity(paramsJson));
httppost.addHeader("content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
You would be better off using the JSON String directly instead of parsing it here. Hope it helps
Try this,It may help u
public void executeHttpPost(String string) throws Exception
{
//This method for HttpConnection
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("URL");
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("Name",string));
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
client.execute(request);
System.out.println("after sending :"+request.toString());
}
catch(Exception e) {System.out.println("Exp="+e);
}
}
I have a problem in posting the data to server by using httpput methods in android.I have to send feedback to server and getting json response. but i am getting 404 bad request. but i dont know where is the problem.
I am strucked here and didn't find any solution. Any suggestions?
My code is as follows:
HttpClient client = new DefaultHttpClient();
HttpPut put = new HttpPut(getString(R.string.feedBack));
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("userId", "8"));
pairs.add(new BasicNameValuePair("feedback",feedbackMessage
.getText().toString()));
put.addHeader("Content-Type", "application/json");
put.addHeader("Accept", "application/json");
put.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(put);
Log.d(tag, "Result" + response.getStatusLine());
You are not initializing a URL object and passing in simple String.
You should do this instead:
URL url = new URL(getString(R.string.feedBack));
HttpClient client = new DefaultHttpClient();
HttpPut put= new HttpPut(url);
And it should work.
I have an example json as below:
{
"Passwd":"String content",
"Userme":"String content"
}
how to construct the JSON String as above and give it as argument to HttpPost in Android.?
Can anyone help me in sorting out this issue.
thanks in Advance,
You can make use of JSONObject to create a simple json like { "Passwd":"String content", "Userme":"String content" } try something like this.
String json="";
JSONObject jobj = new JSONObject();
jobj.put("Userme", "Username");
jobj.put("Passwd", "PasswordValue");
json = jobj.toString();
Above String can be sent as one of the parameter using HTTP POST easily. Below function takes url and json as parameters to make POST request.
private void httpPost(String json,String url) throws ClientProtocolException, IOException{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("json", json));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpClient.execute(httpPost);
}