Sending POST data to website and getting answer - java

I have a problem with getting direct link to video. I want to play it in my WebView/VideoView. How to send POST request and recieve answer with direct link from website which decode such things:
videotools.12pings.net
Is there any way to do that?
Example: put link in the website form - than click a button - direct link is ready under the button

final HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
HttpConnectionParams.setConnectionTimeout(httpParameters, 7000);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse response = client.execute(new HttpGet(path));
HttpEntity entity = response.getEntity();
InputStream imageContentInputStream = entity.getContent();
path is the variable that contains your URL

I hope this will help you..
*You need to get
httpcomponents-client-4.1.zip and apache-mime4j-0.6.1-bin.zip
Add
apache-mime4j-0.6.1-bin.zip
and
httpclient-4.1.jar
httpcore-4.1.jar
httpmime-4.1.jar
from the lib folder in httpcomponents-client-4.1.zip
- See more at: http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/#sthash.N7qT8apH.dpuf*
try {
MultipartEntity multipart = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
FormBodyPart office = new FormBodyPart("office",
new StringBody(getOffice));
multipart.addPart(office);
String imageCount = Integer.toString(drawableList.size());
System.out.println("ImageCount : " + imageCount);
FormBodyPart imgNo = new FormBodyPart("imgNo", new StringBody(
imageCount));
multipart.addPart(imgNo);
} catch (Exception e) {
// TODO: handle exception
}
try {
System.out.println("result : " + multipart.getContentLength());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(CommunicatorUrl.ADD_INCIDENT);
httppost.setEntity(multipart);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// print responce
outPut = EntityUtils.toString(entity);
} catch (Exception e) {
Log.e("log_tag ******",
"Error in http connection " + e.toString());
}
basically this MultipartEntity is useful for sending multiple images and datas to server using post method

String paramUsername = "username";
String paramPassword = "password";
System.out.println("*** doInBackground ** paramUsername " + paramUsername + "
paramPassword :" + paramPassword);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.xxxxxxxxxxxxxx.php");
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("ParamUsername", paramUsername);
BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", paramPassword);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePAir);
try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
httpPost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}

Related

Upload image to Spring Server API in Android

i'm traying to upload a image in Android App to my api, but i have this menssage:
"The current request is not a multipart request"
I've this code in my app android:
#Override
protected String doInBackground(String... uri) {
// url where the data will be posted
String postReceiverUrl = "http://...";
Log.v("TEST", "postURL: " + postReceiverUrl);
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
try {
// the URL where the file will be posted
File file = new File(mCurrentPhotoPath);
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("TEST ", "Response: " + responseStr);
// you can add an if statement here and do other actions based on the response
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
And in my API i've this code:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public
#ResponseBody
String handleFileUpload(#RequestParam(value = "file", required = false) MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
File file1 = new File("test.jpg");
FileOutputStream fos = new FileOutputStream(file1);
BufferedOutputStream stream =
new BufferedOutputStream(fos);
stream.write(bytes);
stream.close();
System.out.println("The path is: ");
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getPath());
return "You successfully uploaded \"test.jpg\"!";
} catch (Exception e) {
return "You failed to upload test.jpg => " + e.getMessage();
}
} else {
return "You failed to upload test.jpg because the file was empty.";
}
}
How can i do this?
May be the following code help to you to upload the image in server
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(<server api url>);
MultipartEntity entity = new MultipartEntity();
File myFile = new File(<file_path>);
FileBody fileBody = new FileBody(myFile);
entity.addPart("upload_param_name",fileBody);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
HttpEntity r_entity = response.getEntity();
xmlString = EntityUtils.toString(r_entity);
Log.d("SOAP ", "Result : " + xmlString.toString());
Also for this, you have to use the .jar of apache-mine and httpmine in your apps libs folder.
Finally i convert the image in base64 and send to server how a String and in my Server reconvert to image.
Thanks!

Android do PATCH/PUT to server

I'm having this issue and I need to put or patch data to the server. I know how to do a standard post, but how can I do this PATCH or PUT to the server?
The URL to the server is PATCH to www.example.com/api/documents and parameter is doc_id(integer).
This is what I currently have
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("content-type", "application/json");
httpPost.setHeader("accept-charset", "utf8");
try {
HttpResponse response = httpClient.execute(httpPost);
responseString = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
Log.e("Request exception:", "excpetion", e);
}
return responseString;
But this code I think is wrong as hell :)
This is the most common way---
Creating jsonObj and putting json values:
JSONObject jsonObj = new JSONObject();
jsonObj .put("doc_id", <put your value> + "");
String response = callPutService(source, password, callingAPI, jsonObj);
This is the callPutService that is called:
public String callPutService(String userName, String password,
String type, JSONObject jsonObject) {
String line = null, jsonString = "";
HttpResponse response = null;
InputStream inputStream = null;
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.
setConnectionTimeout
(client.getParams(), 20000); // Timeout Limit
HttpPut put = new HttpPut(WEBSERVICE + type);
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentType("application/json;charset=UTF-8");
put.setHeader("Authorization",
"basic " + Base64.
encodeToString((userName + ":" + password).getBytes(),
Base64.URL_SAFE | Base64.NO_WRAP));
put.setEntity(se);
response = client.execute(put);
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode == 200){
//do whatever
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonString;
}

Use arabic text in android

How to get the arabic string in json format and how to display in android application
inputStreamReader. I get the json from server side And using the Windows-1256 encodingString to convert the arabic string but sometext not be shown correctly.
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
System.out.println(url + ":::url");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream,"windows-1256");
//new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader,8);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out
.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
I have been r & d around a day and finally success to parse my arabic json response getting from server using following code.So, may be helpful to you.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(Your_URL);
HttpResponse http_response= httpclient.execute(httppost);
HttpEntity entity = http_response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.i("Response", jsonText);
Now, use jsonText for your further requirement.
Thank You

Parse Json Arabic text

I can't parse Arabic/Persian text from SQL database. Everything is set to UTF-8. My SQL database text is set to utf8_general_ci. JSON parser is set to UTF-8 too.
Text is shown good in English. But when I use Arabic/Persian text in database, android shows text as ???????.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have been r & d around a day and finally success to parse my arabic json response getting from server using following code.So, may be helpful to you.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(Your_URL);
HttpResponse http_response= httpclient.execute(httppost);
HttpEntity entity = http_response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.i("Response", jsonText);
Now, use jsonText for your further requirement.
Thank You
Maybe the problem is on server side. Check the raw String you got from the Server to see if it is correctly formatted.
I think it can help you by storing it as clob/blob, since once you have the bytes which were convereted from UTF-8 at server side, any client side code can also then using various String encoding formats to display the test.
Or my other advice, use a webview to display it, its more mature to handle these nuances.

Send key-value parametres and json message body throught http post request

I need to send http POST request from mobile android application to the server side applcation.
This request need to contain json message in body and some key-value parametres.
I am try to write this method:
public static String makePostRequest(String url, String body, BasicHttpParams params) throws ClientProtocolException, IOException {
Logger.i(HttpClientAndroid.class, "Make post request");
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(body);
httpPost.setParams(params);
httpPost.setEntity(entity);
HttpResponse response = getHttpClient().execute(httpPost);
return handleResponse(response);
}
Here i set parametres to request throught method setParams and set json body throught setEntity.
But it isn't work.
Can anybody help to me?
You can use a NameValuePair to do this..........
Below is the code from my project where I used NameValuePair to sent the xml data and receive the xml response, this will provide u some idea about how to use it with JSON.
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}

Categories