HttpGet httpget = new HttpGet("http://www.google.com/");
System.out.println("executing request " + httpget.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
this will get responseBody as "string" , how to get btye[] with httpclient.execute(..) ? the reason i want to get byte[] is because i want to write to some other outputstream
public byte[] executeBinary(URI uri) throws IOException, ClientProtocolException {
HttpGet httpget = new HttpGet(uri);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
entity.writeTo(baos);
return baos.toByteArray();
}
You can use the responseBody.getBytes() to get byte[].
Try HttpResponse.getEntity().writeTo(OutputStream)
Related
i Want to send arabic (unicode) with the HTTP Request
When using URLEncodedUtils.format(params, HTTP.UTF_8);
it give paramString this value when the words are in arabic
"%D8%A7%D9%84%D9%82%D8%A7%D9%87%D8%B1%D9%87"
This is my code:
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
Log.d("Parser" , paramString);
url += "?" + paramString;
Log.d("parser" , url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
The Server Code
function getShippingAddress($email)
{
$customerAddress = Mage::getModel('customer/address');
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
$defaultShippingId = $customer->getDefaultShipping();
$customerAddress->load($defaultShippingId);
$response["success"] = 1;
$response["data"][0] = $customerAddress->getData('city');
$response["data"][1] = $customerAddress- >getData('street');
$response["data"][2] = $customerAddress->getData('telephone');
header('Content-Type: application/json; charset=utf-8');
return json_encode($response);
}
Try sending parameter using POST. Sample code is here:
private String sendHttpPost(String url, String msg)
throws Exception {
HttpPost post = new HttpPost(url);
StringEntity stringEntity = new StringEntity(msg, "UTF-8");
post.setEntity(stringEntity);
return execute(post);
}
or try this :
String unicodeUrl = URLEncoder.encode(url += "?" + paramString, "UTF-8");
HttpPost post = new HttpPost(unicodeUrl);
UPDATE:
if your params ="Some_String_In_Arabic", try this code :
DefaultHttpClient httpClient = new DefaultHttpClient();
//String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
String unicodeUrl = URLEncoder.encode(url += "?" + params, "UTF-8");
Log.d("URL" , unicodeUrl);
HttpGet httpGet = new HttpGet(unicodeUrl);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
and use urldecode method (of PHP) in your server side to get the string back in arabic form.
HttpPost showing the file upload status, I want to make progressbar. How can I do.
thanks
public void post(String url, File sendFile) throws UnsupportedEncodingException, IOException {
HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(url);
MultipartEntity multiEntity = new MultipartEntity();
multiEntity.addPart("userfile", new FileBody(sendFile));
post.setEntity(multiEntity);
HttpResponse response = client.execute(post);
if (response != null) {
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
}
Not sure if apache httpclient has a ready-made solution for this but you could use an InputStreamBody (instead of FileBody) and wrap the FileInputStream in something that counts how much is already read. Compare this to the size of the file to see how far along you are.
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
I am trying to upload file but i am not doing it through html form. QueryParam and PathParam can't be used. So can anyone tell how to pass stream.
My HttPClient looks like:
try
{
HttpClient httpclient = new DefaultHttpClient();
InputStream stream=new FileInputStream(new File("C:/localstore/ankita/Desert.jpg"));
String url="http://localhost:8080/Cloud/webresources/fileupload";
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
}
catch(Exception e){}
and my web service class looks somewhat like:
#Path("/fileupload")
public class UploadFileService {
#POST
#Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response uploadFile(InputStream in) throws IOException
{
String uploadedFileLocation = "c://filestore/Desert.jpg" ;
// save it
saveToFile(in, uploadedFileLocation);
String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
// save uploaded file to new location
private void saveToFile(InputStream uploadedInputStream,String uploadedFileLocation)
{
try {
OutputStream out = null;
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Can anyone help??
String url="http://localhost:8080/Cloud/webresources/fileupload";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(new File("C:/localstore/ankita/Desert.jpg")), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
How web service will look like?
You can't do it that way. You can't pass a stream in an HTTP request, because streams are not serializable.
The way to do this is to is create an HttpEntity to wrap the stream (e.g. an InputStreamEntity) then attach it to the HttpPOST object using setEntity. Then the POST is sent, the client will read from your stream and send the bytes as the request's "POST data".
I'm trying to Get Request with code below but the stringbuilder is always null. The url is correct...
http://pastebin.com/mASvGmkq
EDIT
public static StringBuilder sendHttpGet(String url) {
HttpClient http = new DefaultHttpClient();
StringBuilder buffer = null;
try {
HttpGet get = new HttpGet(url);
HttpResponse resp = http.execute(get);
buffer = inputStreamToString(resp.getEntity().getContent());
}
catch(Exception e) {
debug("ERRO EM GET HTTP URL:\n" + url + "\n" + e);
return null;
}
debug("GET HTTP URL OK:\n" + buffer);
return buffer;
}
I usually do it like this:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
}
where output is a String-object.