Send JSON array in java by POST method - java

I have a json array prepared for send to a php server. When I tried to send it by GET method it tells the URL is too long. So I decided to send it by POST. I would like to know is there any way to do it successfully?

As you give no details about any library you use, this is somehow vage. But you could have a look at http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/ under point 3. to see how this can be achieved.

i used this code to send my json string
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
public static String POST(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "what ever your string is";
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException
{
// TODO Auto-generated method stub
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
use this to execute request
new HttpAsyncTask().execute("your URL");

Related

No response from HTTP request

i have written an android app which post data to my database. The app should access an webservice which post the data to the database. the webservice works fine. ive testet it with my browser, he is already on the server. now i want my app to execute the webservice. but that doesnt work. My debugger doesnt work too so im not able to debug. here is my code to for accessing the webservice. any ideas??
public class PostBlog extends AsyncTask<String, Void, String> {
String BlogURL;
public PostBlog(String insertBlogURL) {
BlogURL = insertBlogURL;
}
#Override
protected String doInBackground(String... params) {
postBlogData(BlogURL);
return null;
}
public void postBlogData(String url) {
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1980"));
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
//(TextView)rootView.findViewById(R.id.question)
Log.e("log_tag", "Error converting result " + e.toString());
}
}
}
The Class is called from my main Activity by
new PostBlog(insertBlogURL).execute("");
Is there another easier way to execute my ".jsp?asdd=sdsd" file on the server?
Thanks for your ideas.
Instead of doing :
new PostBlog(insertBlogURL).execute("");
Change your constructor and retrieve the url from the doInBackground method, by doing params[0]
Then initiate the download like this
PostBlog blogPoster = new PostBlog();
try {
blogPoster.execute(insertBlogURL);
} catch (InterruptedException e) {} catch (ExecutionException e) {}
I should say this is a modified snippet of code from my own project, so it might not work exactly the way you expect.

how to call web service in java using post method

public static String[] Webcall(String emailID) {
try {
URL url = new URL(AppConfig.URL + emailID);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "application/json");
conn.setRequestProperty("userEmailId", emailID);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
org.json.JSONObject _jsonObject = new org.json.JSONObject(output);
org.json.JSONArray _jArray = _jsonObject.getJSONArray("manager");
String[] str = new String[_jArray.length()];
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
This is my code I am trying to call web service and get data.
But when I hit web service then I am getting below exception
Failed : HTTP error code : 404
Please suggest me where am doing wrong try to give solution for this .
The first thing is check url is it working on computer using postman or restclient and if it is working fine then tried to post using below code, this code is for posting data in json format using HttpPost you can use retrofit lib as Milad suggested.
public static String POST(String url, String email)
{
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email", email);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
I think u should try to re-check URL that you send request to.
follow the output error, code 404 that mean the URL is broken or dead link.
You can do the same by using jersy-client and jersy core.Here is the code snippet
private static void generateXML(String xmlName, String requestXML, String url)
{
try
{
Client client = Client.create();
WebResource webResource = client
.resource(url);
ClientResponse response = (ClientResponse)webResource.accept(new String[] { "application/xml" }).post(ClientResponse.class, requestXML);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = (String)response.getEntity(String.class);
PrintWriter writer = new PrintWriter(xmlName, "UTF-8");
writer.println(output);
writer.close();
}
catch (Exception e) {
try {
throw new CustomException("Rest-Client May Be Not Working From Your System");
} catch (CustomException e1) {
System.exit(1);
}
}
}
Call this method from your code with varibales.

Post JSON in android

I want to post String data over HttpClient in android
but i'm tired after receive response status code 503 - service unavailable and
return response as Html code for our url.
I write in the following Code in JAVA Application and i return the data but when I write the same code in Android Application i receive an exception file I/O not found, I'm Puzzled for this case:
public void goButton(View v)
{
try{
URL url = new URL("https://xxxxxxxxx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Test ts= new ApiRequest("null","getUserbyID",new String[] { "66868706" });
String payLoad = ts.toString(); //toSting is override method that create //JSON Object
System.out.println("--->>> " + payLoad);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
System.out.println("=================>>> "+ payLoad);
wr.write(payLoad);
wr.flush();
BufferedReader rd = new BufferedReader(new nputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("-->> " + line);
response += line;
}
wr.close();
rd.close();
System.out.println("=================>>> "+ response);
} catch (Exception e) {
e.printStackTrace();
System.out.println("=================>>> " + e.toString());
throw new RuntimeException(e);
}
I try to put this code in AsynTask, Thread but i receive the same response status code.
I write in the following Android code as an example data
public void goButton(View v)
{
try{
new Thread(new Runnable() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000); // Timeout Limit
HttpResponse response;
String url = "https://xxxxxxxxxxxxx";
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
json.put("service","null");
json.put("method", getUserByID.toString());
json.put("parameters", "1111");
System.out.println(">>>>>>>>>>>" + json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
String response = client.execute(post);
if (response != null) {
String temp = EntityUtils.toString(response.getEntity());
System.out.println(">>>>>>>>>>>" + temp);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(">>>>>>>>>>>" + e.getMessage());
}
}
}).start();
}
Please Help me to find solution for this problem :(
Thank you in advance
Here is an code snippet , hoping it will help you.
1)An function which carries the http get service
private String SendDataFromAndroidDevice() {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet("your url + data appended");
BufferedReader in = null;
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(getMethod);
in = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2) An Class which extends AsyncTask
private class HTTPdemo extends
AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
String result = SendDataFromAndroidDevice();
return result;
}
#Override
protected void onProgressUpdate(Void... values) {}
#Override
protected void onPostExecute(String result) {
if (result != null && !result.equals("")) {
try {
JSONObject resObject = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3) Inside your onCreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("your layout");
if ("check here where network/internet is avaliable") {
new HTTPdemo().execute("");
}
}
This code snippet ,
Android device will send the data via URL towards Server
now server needs to fetch that data from the URL
Hey Mohammed Saleem
The code snippet provided by me works in the following way,
1)Android device send the URL+data to server
2)Server [say ASP.NET platform used] receive the data and gives an acknowledgement
Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is
Server needs to receive the data
An webservice should be used to do that
Implement an webservice at server side
The webservice will be invoked whenever android will push the URL+data
Once you have the data ,manipulated it as you want

Illegal State Exception error: target host must not be null or set in parameters

I ran my app on my old galaxy s and it worked fine and then I my nexus s and it started giving me a few errors. I was getting an illegal character in path error in my JSONParser that I fixed by using URLEncoder.encode but now I am getting an illegal state exception error. I looked here http://blog.donnfelker.com/2010/04/29/android-odd-error-in-defaulthttpclient/
but I already had http:// in my url. I checked the debugger for the uri of my httpget. I am not exactly sure what I am looking for here. I know that I am trying to find if a character has been encoded that shouldn't have been as suggest in the comments of the article I linked to above but I am not sure how how to go about doing that. When I click on my uri under httpGet in the JSONParser.doInBackground method I get %5BLjava.lang.String%3B%4042b3f010. Am I correct that this is the encoded representation from the URLEncoder.encode? I pass in to my JSONParser.doInBackground a url of the type StringBuilder that I convert to String and then encode. The myURL entry in the debugger gives me the same as the uri: %5BLjava.lang.String%3B%4042b3f010. Am I going about doing this correctly. Thank for any help. These are what I believe to be the relevant parts of my code:
public class JSONParser extends AsyncTask<String, Void, JSONObject> {
static InputStream inputStream = null;
static JSONObject jObject = null;
static String jSon = "";
protected JSONObject doInBackground(String... url) {
// TODO Auto-generated method stub
//Make HTTP Request
try {
//defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
String myURL = url.toString();
myURL = URLEncoder.encode(myURL, "utf-8");
HttpGet httpGet = new HttpGet(myURL);
//header
httpGet.setHeader("Accept", "application/json");
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
Log.d("JSON Contents", stringBuilder.toString());
inputStream.close();
jSon = stringBuilder.toString();
} catch (Exception e){
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//try to parse the string to JSON Object
try {
jObject = new JSONObject(jSon);
} catch (JSONException e){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//return JSON String
return jObject;
}
}
This is how I am building the url that I pass through to the parser:
public class getName {
static String nameOne = null;
static String nameTwo = null;
static StringBuilder personURLOne = new StringBuilder();
static StringBuilder personURLTwo = new StringBuilder();
public static String personURL = "http://api.themoviedb.org/3/search/person?api_key=bb0b6d66c2899aefb4d0863b0d37dc4e&query=";
public static StringBuilder getName1(EditText searchOne){
nameOne = searchOne.getText().toString();
nameOne = nameOne.replace(" ", "_");
personURLOne.append(personURL);
personURLOne = personURLOne.append(nameOne);
return personURLOne;
}
Appreciate any help
UPDATE - I changed my code to the following in my JSONParser:
public class JSONParser extends AsyncTask<String, Void, JSONObject> {
static InputStream inputStream = null;
static JSONObject jObject = null;
static String jSon = "";
public String myURL;
protected JSONObject doInBackground(String... url) {
// TODO Auto-generated method stub
//Make HTTP Request
try {
//defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
for(int i = 0; i < url.length; i++){
myURL = url[0];
myURL = URLEncoder.encode(myURL, "utf-8");
}
HttpGet httpGet = new HttpGet(myURL);
If you URL decode this %5BLjava.lang.String%3B%4042b3f010 you get [Ljava.lang.String;#42b3f010.
That's pretty suspicious, it's not a URL. When you call toString on an array, you get that funny looking string with an open bracket. For instance an array of ints prints out something like [I#33f42b49.
This is because url in your doInBackGround method is actually an array of Strings, not a String, because doInBackground takes a variable number of String parameters: doInBackground(String... That ellipses indicates a method with varags. So you don't want to call toString on it at all.
Instead you'll want to iterate over it and download all of them, or just take the first: url[0]. I'd rename it to urls too, just to make it obvious :)

Retrieve the http code of the response in java

I have the following code for make a post to an url an retrieve the response as a String. But I'd like to get also the HTTP response code (404,503, etc). Where can I recover it?
I've tried with the methods offered by the HttpReponse class but didn't find it.
Thanks
public static String post(String url, List<BasicNameValuePair> postvalues) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
if ((postvalues == null)) {
postvalues = new ArrayList<BasicNameValuePair>();
}
httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return requestToString(response);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static String requestToString(HttpResponse response) {
String result = "";
try {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
You can modify your code like this:
//...
HttpResponse response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//edit: there is already function for this
return EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
//Houston we have a problem
//we should do something with bad http status
return null;
}
EDIT: just one more thing ...
instead of requestToString(..); you can use EntityUtils.toString(..);
Have you tried this?
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
response.getStatusLine().getStatusCode();
Have you tried the following?
response.getStatusLine().getStatusCode()

Categories

Resources