I have the following code snippet that tries to make an HTTP call to my servlet:
try {
// Construct data
String data = URLEncoder.encode("rpt_type", "UTF-8") + "=" + URLEncoder.encode(reportType, "UTF-8");
data += "&" + URLEncoder.encode("rpt_project", "UTF-8") + "=" + URLEncoder.encode(reportProject, "UTF-8");
data += "&" + URLEncoder.encode("rpt_mrv_creator", "UTF-8") + "=" + URLEncoder.encode(reportMrvCreator, "UTF-8");
data += "&" + URLEncoder.encode("rpt_gi_recipient", "UTF-8") + "=" + URLEncoder.encode(reportGiRecipient, "UTF-8");
data += "&" + URLEncoder.encode("rpt_plant", "UTF-8") + "=" + URLEncoder.encode(reportPlant, "UTF-8");
data += "&" + URLEncoder.encode("rpt_sloc", "UTF-8") + "=" + URLEncoder.encode(reportStorageLoc, "UTF-8");
data += "&" + URLEncoder.encode("rpt_gi_no", "UTF-8") + "=" + URLEncoder.encode(reportGiNo, "UTF-8");
data += "&" + URLEncoder.encode("date_sap_gi_fr", "UTF-8") + "=" + URLEncoder.encode(reportDateGiFrom, "UTF-8");
data += "&" + URLEncoder.encode("date_sap_gi_to", "UTF-8") + "=" + URLEncoder.encode(reportDateGiTo, "UTF-8");
data += "&" + URLEncoder.encode("rpt_partno", "UTF-8") + "=" + URLEncoder.encode(reportPartNo, "UTF-8");
data += "&" + URLEncoder.encode("rpt_so_no", "UTF-8") + "=" + URLEncoder.encode(reportSvcOrderNo, "UTF-8");
data += "&" + URLEncoder.encode("date_scan_fr", "UTF-8") + "=" + URLEncoder.encode(reportDateScanFrom, "UTF-8");
data += "&" + URLEncoder.encode("date_scan_to", "UTF-8") + "=" + URLEncoder.encode(reportDateScanTo, "UTF-8");
System.out.println("[data]\n" + data);
// Send data
String urlString = "http://localhost:8080/aerobook/GIStatusReportDownload?" + data;
System.out.println("[url] " + urlString);
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
//conn.setDoOutput(true);
//OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//wr.write(data);
//wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
//wr.close();
rd.close();
} catch (Exception e) {
}
My debug output:
[data]
rpt_type=d&rpt_project=aaa&rpt_mrv_creator=bbb&rpt_gi_recipient=ccc&rpt_plant=ddd&rpt_sloc=eee&rpt_gi_no=fff&date_sap_gi_fr=02%2F05%2F2012&date_sap_gi_to=03%2F05%2F2012&rpt_partno=ggg&rpt_so_no=hhh&date_scan_fr=26%2F05%2F2012&date_scan_to=31%2F05%2F2012
[url] http://localhost:8080/aerobook/GIStatusReportDownload?rpt_type=d&rpt_project=aaa&rpt_mrv_creator=bbb&rpt_gi_recipient=ccc&rpt_plant=ddd&rpt_sloc=eee&rpt_gi_no=fff&date_sap_gi_fr=02%2F05%2F2012&date_sap_gi_to=03%2F05%2F2012&rpt_partno=ggg&rpt_so_no=hhh&date_scan_fr=26%2F05%2F2012&date_scan_to=31%2F05%2F2012
On my servlet (in a separate file from the code above), I generate an Excel file for download:
res.setContentType(sContentType);
res.setHeader("Content-Disposition", "attachment;filename=\"" + sExcelFileName + "\"");
OutputStream oOutStrm = res.getOutputStream();
wbBook.write(oOutStrm);
oOutStrm.close();
My issue here is that from the URL generated by my code (as shown in the debug output above), I can access my servlet and I manage to get the Save-As dialog.
I'd like to get the contents of the file generated for use within my code. Is there any way I can get the attachment from my code, in byte stream or any other format?
Edit #3: Cleaned up the top
When you enter the URI into the browser, you are doing a GET request. Your client Java code however produces a POST request, and sends the parameters in the body, not the URI.
You may want to look at an HTTP trace and compare.
I want to get the contents of the excel file on my code, but so far it's not working.
I find no errors in the code.
I believe you want to convert content from input stream to an HSSFWorkbook object.
Following code snippet will help you on it.
java.net.URLConnection conn = url.openConnection();
java.io.InputStream is = conn.getInputStream();
org.apache.poi.hssf.usermodel.HSSFWorkbook workBook = new org.apache.poi.hssf.usermodel.HSSFWorkbook( is );
System.out.println( "Number of Sheets: " + workBook.getNumberOfSheets() );
org.apache.poi.hssf.usermodel.HSSFSheet sheet = workBook.getSheetAt( 0 );
System.out.println( "Sheet Name: " + sheet.getSheetName() );
// rest of your code to handle the captured workBook
// cheers
Check wbBook.write(oOutStrm); whether anything has been written into outputStream, also you need call oOutStrm.flash() before close it.
I doubt that the problem lies at OutputStream oOutStrm = res.getOutputStream();.
I bet res is HttpServletResponse and it returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data
Check API
So, You might not be getting anything except fileName.
In Servlet Try
FileOutputStream stream = new FileOutputStream("c:/excel/Book1.xls");
workBook.write(stream);
Related
I'm building an app for a company that communicates with MySQL database, I'm trying to send a new entry to the server, but I can't get the outputstream write method to work, I know there's an error but I can't seem to find a solution
Here's my code:
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new OutputStream() {
#Override
public void write(int b) throws IOException {
Log.e("Car DetailStream Writer","outputStreamWriter write method called");
try {
int isLargeAsInt = car.isLarge() ? 1 : 0;
int isDieselAsInt = car.isDiesel() ? 1 : 0;
Log.e("Car Details Write Data",car.getCarModel());
writeData =
URLEncoder.encode("carModel", "UTF-8") + "=" + URLEncoder.encode(car.getCarModel(), "UTF-8") + "&" +
URLEncoder.encode("carYear", "UTF-8") + "=" + URLEncoder.encode(car.getYear(), "UTF-8") + "&" +
URLEncoder.encode("carPlate", "UTF-8") + "=" + URLEncoder.encode(car.getPlateNumber(), "UTF-8") + "&" +
URLEncoder.encode("isLarge", "UTF-8") + "=" + isLargeAsInt + "&" +
URLEncoder.encode("isDiesel", "UTF-8") + "=" + isDieselAsInt + "&" +
URLEncoder.encode("currentMileage", "UTF-8") + "=" + car.getCurrentMileage();
Log.e("Written Data", writeData);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
Log.d("Buffered Writer","Buffered Writer Created");
bufferedWriter.write(writeData);
bufferedWriter.flush();
and here's the error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at java.io.Writer.write(Writer.java:157)
at com.example.trknil.turknilmanagement.utils.SendUtils.makeHttpRequest(SendUtils.java:124)
and this is line 124:
bufferedWriter.write(writeData);
Can anyone fix the code please and tell me where I went wrong.
I am developing an app plays song and communicates with a server. The methods are addMusic, deleteMusic, and requestMusicList. All of them uses http GET method.
Here's The Case:
deleteMusic, and requestMusicList works fine in all phones. Except for addMusic, which only works in some phone.
addMusic only works in Samsung phone. While in nuu, mi, and meizu. Those are the phones that we got here, so we only tested the app with those phones.
My Problem:
Since the parameters included in the addMusic url string contains Chinese characters, I think this is the cause of the problem. Here is the log.
08-06 15:00:22.102: V/HttpConnectionManager(13211): Get url string is http://115.28.6.88:7100/cgi-bin/v1/music_add?content_url=http://fdfs.xmcdn.com/group12/M07/03/65/wKgDW1VQa-6iJ2e1AB7JjcEKs2E684.mp3&cover_image_url=http://fdfs.xmcdn.com/group11/M02/03/7B/wKgDa1VQbA2j2mOpAAiTLl27BzM875_mobile_small.jpg&dev_id=test101&duration=252×tamp=1438844422&title=《Couldyoustaywithme》张靓颖(电视剧《洋嫁》主题曲)&type=type_habit&sign=f834a4667004cebdac1516584b4a4930
08-06 15:00:22.272: I/Adreno200-EGLSUB(13211): <ConfigWindowMatch:2252>: Format RGBA_8888.
08-06 15:00:22.342: V/HttpConnectionManager(13211): Response code from GET: 200
08-06 15:00:22.352: V/DetailManager(13211): Handled http response is {"retcode": 100004, "retinfo": "check sign fail, request_sign:[F834A4667004CEBDAC1516584B4A4930], mysign:[EBFA4D2D40F20DF1B124375A0D9FAD38], mysign_src_nokey:[content_url=http://fdfs.xmcdn.com/group12/M07/03/65/wKgDW1VQa-6iJ2e1AB7JjcEKs2E684.mp3&cover_image_url=http://fdfs.xmcdn.com/group11/M02/03/7B/wKgDa1VQbA2j2mOpAAiTLl27BzM875_mobile_small.jpg&dev_id=test101&duration=252×tamp=1438844422&title=?Couldyoustaywithme????????????????&type=type_habit]"}
08-06 15:00:22.352: V/AudioFragment(13211): Server request failed: check sign fail, request_sign:[F834A4667004CEBDAC1516584B4A4930], mysign:[EBFA4D2D40F20DF1B124375A0D9FAD38], mysign_src_nokey:[content_url=http://fdfs.xmcdn.com/group12/M07/03/65/wKgDW1VQa-6iJ2e1AB7JjcEKs2E684.mp3&cover_image_url=http://fdfs.xmcdn.com/group11/M02/03/7B/wKgDa1VQbA2j2mOpAAiTLl27BzM875_mobile_small.jpg&dev_id=test101&duration=252×tamp=1438844422&title=?Couldyoustaywithme????????????????&type=type_habit]
As can be seen in the first line, this contains the URL that I sent. The URL contains these "张靓颖(电视剧《洋嫁》主题曲" Chinese characters under the title parameter. When the server returns a response, these characters became "??????????????".
Please take not that this issue only occurs in the said Android phones(mi, meizu, and nuu). For Samsung, this NEVER occured.
Here is the code of my addMusic method:
public void addMusic(final Music music)
{
new Thread(new Runnable()
{
#Override
public void run()
{
String contentURL = KEY_CONTENT_URL + "=" + music.mContentURL;
String coverImageURLData = "&" + KEY_COVER_IMAGE_URL + "=" + music.mCoverImageURL;
String deviceIDData = "&" + KEY_DEVICE_ID + "=" + mDeviceID;
String duration = "&" + KEY_DURATION + "=" + Long.toString(music.mDuration);
String timestamp = "&" + KEY_TIMESTAMP + "=" + Long.toString(System.currentTimeMillis()/1000);
String titleData = "&" + KEY_TITLE + "=" + music.mTitle.replaceAll("\\s", "");
String typeData = "&" + KEY_TYPE + "=" + music.mType;
String dataArrayString = contentURL + coverImageURLData + deviceIDData + duration + timestamp + titleData + typeData;
String key = "&" + KEY_KEY + "=" + KEY;
String sign = "&" + KEY_SIGN + "=" + Utilities.getMD5String(dataArrayString + key);
String parametersURL = dataArrayString + sign;
try
{
handleHttpResponse(mConnectionManager.get(URL_MAIN + URL_ADD_MUSIC + parametersURL), REQUEST_CODE_ADD_MUSIC);
}
catch (IOException e)
{
e.printStackTrace();
mListener.onServerRequestFail(e.getLocalizedMessage());
}
}
}).start();
}
Here is the code of Http GET:
public String get(String urlString) throws IOException
{
Log.v(LOG_TAG, "Get url string is " + urlString);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = connection.getResponseCode();
Log.v(LOG_TAG, "Response code from GET: " + responseCode);
if(responseCode == RESPONSE_OK)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = reader.readLine()) != null)
{
response.append(inputLine);
}
reader.close();
return response.toString();
}
else
{
return ERROR_NO_RESPONSE;
}
}
I tried checking the defaultCharset, which is "UTF-8" for all phones tested.
How can I solve this? Please help. Many Thanks
------------ Tried URLEncoder.encode(music.mTitle.replaceAll("\s", ""), "UTF-8") ----------------
Here's the Log:
08-06 15:53:08.852: V/HttpConnectionManager(15061): Get url string is http://115.28.6.88:7100/cgi-bin/v1/music_add?content_url=http://fdfs.xmcdn.com/group6/M09/1E/0B/wKgDg1UrI8iw-rGzAAyaxOKiDrc706.mp3&cover_image_url=http://fdfs.xmcdn.com/group6/M00/1E/18/wKgDg1UrJp7TMEMMAAP5a37TPkE290_mobile_small.jpg&dev_id=test101&duration=103×tamp=1438847588&title=%E3%80%8Ayouaremysunshine%E3%80%8B%EF%BC%8D%E5%BC%A0%E9%9D%93%E9%A2%96%EF%BC%88%E7%94%B5%E5%BD%B1%E3%80%8A%E4%BD%95%E4%BB%A5%E7%AC%99%E7%AE%AB%E9%BB%98%E3%80%8B%E8%8B%B1%E6%96%87%E6%8F%92%E6%9B%B2&type=type_habit&sign=f7b8c5a0cb1fceb32a54b428311744ad
08-06 15:53:08.902: I/Adreno200-EGLSUB(15061): <ConfigWindowMatch:2252>: Format RGBA_8888.
08-06 15:53:19.692: V/HttpConnectionManager(15061): Response code from GET: 200
08-06 15:53:19.692: V/DetailManager(15061): Handled http response is {"retcode": 100004, "retinfo": "check sign fail, request_sign:[F7B8C5A0CB1FCEB32A54B428311744AD], mysign:[537721D351DF6C8B40C62C4F8672EADF], mysign_src_nokey:[content_url=http://fdfs.xmcdn.com/group6/M09/1E/0B/wKgDg1UrI8iw-rGzAAyaxOKiDrc706.mp3&cover_image_url=http://fdfs.xmcdn.com/group6/M00/1E/18/wKgDg1UrJp7TMEMMAAP5a37TPkE290_mobile_small.jpg&dev_id=test101&duration=103×tamp=1438847588&title=\u300ayouaremysunshine\u300b\uff0d\u5f20\u9753\u9896\uff08\u7535\u5f71\u300a\u4f55\u4ee5\u7b19\u7bab\u9ed8\u300b\u82f1\u6587\u63d2\u66f2&type=type_habit]"}
08-06 15:53:19.702: V/AudioFragment(15061): Server request failed: check sign fail, request_sign:[F7B8C5A0CB1FCEB32A54B428311744AD], mysign:[537721D351DF6C8B40C62C4F8672EADF], mysign_src_nokey:[content_url=http://fdfs.xmcdn.com/group6/M09/1E/0B/wKgDg1UrI8iw-rGzAAyaxOKiDrc706.mp3&cover_image_url=http://fdfs.xmcdn.com/group6/M00/1E/18/wKgDg1UrJp7TMEMMAAP5a37TPkE290_mobile_small.jpg&dev_id=test101&duration=103×tamp=1438847588&title=《youaremysunshine》-张靓颖(电影《何以笙箫默》英文插曲&type=type_habit]
I solved it. Thanks to #Andy Turner, and #lorenzo-s for the tips in the comment.
My mistake is that I encoded the string to UTF-8 before getting the MD5 checksum. I noticed that when I send the request(URLEncoded) to the server, the response containing the title is correct. The error was only about the MD5 sign check.
The correct way is to get the MD5 checksum first without encoding the title parameter. Then before appending the title parameter to the URL String, convert it to UTF-8.
Thank you #Andy Turner for reminding me that I have to deal with the "&" in the parameter.
i had some difficulties in programming and the meaning of the Request Body is confused. It always returns 400 response codes.Please help me.
String baseURL="https://sb-ssl.google.com/safebrowsing/api/lookup";
String arguments = "";
arguments+=URLEncoder.encode("client", "UTF-8")+"="+URLEncoder.encode("demo-app", "UTF-8")+"&";
arguments+=URLEncoder.encode("apikey", "UTF-8")+"="+URLEncoder.encode("apikey", "UTF-8")+"&";
arguments+=URLEncoder.encode("appver", "UTF-8")+"="+URLEncoder.encode("1.5.2", "UTF-8")+"&";
arguments+=URLEncoder.encode("pver", "UTF-8")+"="+URLEncoder.encode("3.0", "UTF-8")+"&";
arguments+=URLEncoder.encode("post_req_body", "UTF-8")+"="+URLEncoder.encode("2\nhttp://www.google.com\nhttp://www.facebook.com", "UTF-8");
String query = arguments;
System.out.println("Sending POST request - " + query);
// Construct the url object representing cgi script
URL url = new URL( baseURL );
// Get a URLConnection object, to write to POST method
URLConnection connect = url.openConnection();
// Specify connection settings
connect.setDoInput(true);
connect.setDoOutput(true);
// Get an output stream for writing
OutputStream output = connect.getOutputStream();
PrintStream pout = new PrintStream (output);
pout.print ( query );
pout.close();
Your request is wrong. If you use a POST request, then the parameters client, apikey, apiver and pver should be part of the URL.
The request body should only consist of the URLs to check (plus the number of URLS on the first line).
So it could look like this:
String baseURL="https://sb-ssl.google.com/safebrowsing/api/lookup";
String arguments = "";
arguments + =URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("myapp", "UTF-8") + "&";
arguments + =URLEncoder.encode("apikey", "UTF-8") + "=" + URLEncoder.encode("12341234", "UTF-8") + "&";
arguments + =URLEncoder.encode("appver", "UTF-8") + "=" + URLEncoder.encode("1.5.2", "UTF-8") + "&";
arguments + =URLEncoder.encode("pver", "UTF-8") + "=" + URLEncoder.encode("3.0", "UTF-8");
// Construct the url object representing cgi script
URL url = new URL(baseURL + "?" + arguments);
// Get a URLConnection object, to write to POST method
URLConnection connect = url.openConnection();
// Specify connection settings
connect.setDoInput(true);
connect.setDoOutput(true);
// Get an output stream for writing
OutputStream output = connect.getOutputStream();
PrintStream pout = new PrintStream (output);
pout.print("2");
pout.println();
pout.print("http://www.google.com");
pout.println();
pout.print("http://www.facebook.com");
pout.close();
I am trying to write the following section of php code in java. I will provide the php code and the java code. What I would like help with is a) am I even on the right track and b) the line with the "Please help here" comment, I am unsure of how to do this in java. This line is header("Location: ".$strCitiRedirectURL.$content."");
Thank you in advance.
php code:
$req =& new HTTP_Request($strCitiLoginURL);
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addPostData("instusername", $strInstUsername);
$req->addPostData("institution", $strInstitution);
$req->addPostData("key", $strInstitutionKey);
$req->addPostData("type", "returning");
$response = $req->sendRequest();
if(isset($_GET['showDebug'])){
print $req->_buildRequest();
}
if (PEAR::isError($response)) {
$content = $response->getMessage();
} else {
$content = $req->getResponseBody();
}
/* Check for 44 Character UUID */
if (preg_match($pattern,$content)){
print 'Success';
ob_start();
header("Location: ".$strCitiRedirectURL.$content."");
ob_flush();
/* No UUID. Login to CITI failed. We may need a new user */
}elseif ($content == "- error: learner not affiliated with institution, add learner or provide username and password"){
// Resubmit as a new user
/* Package data up to post to CITI */
$req =& new HTTP_Request($strCitiLoginURL);
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addPostData("instusername", $strInstUsername);
$req->addPostData("institution", $strInstitution);
$req->addPostData("key", $strInstitutionKey);
$req->addPostData("type", "new");
$req->addPostData("first", $strFirst);
$req->addPostData("last", $strLast);
$req->addPostData("email", $strEmail);
$response = $req->sendRequest();
if(isset($_GET['showDebug'])){
print $req->_buildRequest();
}
if (PEAR::isError($response)) {
$content = $response->getMessage();
} else {
$content = $req->getResponseBody();
}
/* Check for 44 Character UUID */
if (preg_match($pattern,$content)){
print 'Success';
ob_start();
/*PLEASE HELP ON THIS LINE*/ header("Location: ".$strCitiRedirectURL.$content."");
ob_flush();
}else{
$errMsg = $errMsg.' <li>CITI Error Returned: '.$content.'.</li>';
}
java code
//****CITI CONFIGURATION****
final String pattern = "([0-9A-\\-]{44})";
final String CitiRedirectUrl = "https://www.citiprogram.org/members/mainmenu.asp?strKeyID=";
final String CitiLoginUrl = "http://www.citiprogram.org/remoteloginII.asp";
//****END CITI CONFIGURATION****
try {
// Construct data
String data = URLEncoder.encode("instusername", "UTF-8") + "=" + URLEncoder.encode(c_form.getCan(), "UTF-8");
data += "&" + URLEncoder.encode("institution", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
data += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode("returning", "UTF-8");
// Send data
URL url = new URL("http://www.citiprogram.org/remoteloginII.asp");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
if (pregMatch(pattern, line)) {
//Do the header part from the php code
} else if (line.equals("- error: learner not affiliated with institution, add learner or provide username and password")) {
// Resubmit as a new user
/* Package data up to post to CITI */
// Construct data
String newdata = URLEncoder.encode("instusername", "UTF-8") + "=" + URLEncoder.encode(c_form.getCan(), "UTF-8");
newdata += "&" + URLEncoder.encode("institution", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
newdata += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
newdata += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode("returning", "UTF-8");
// Send data
OutputStreamWriter newwr = new OutputStreamWriter(conn.getOutputStream());
newwr.write(data);
newwr.flush();
// Get the response
BufferedReader newrd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String newline;
while ((newline = newrd.readLine()) != null) {
System.out.println(newline);
if (pregMatch(pattern, newline)) {
} else {
//Print error message
}
}
}
}
wr.close();
rd.close();
} catch (Exception e) {
}
//Check for 44 character UUID
public static boolean pregMatch(String pattern, String content) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(content);
boolean b = m.matches();
return b;
}
I believe
header("Location: ".$strCitiRedirectURL.$content."");
in PHP would be the same as the following in Java (using your wr object):
wr.sendRedirect("http://path.to.redirect/");
You could also forward the request, but I have a feeling you just want the client to redirect to citirewards or whatever, in which case sendRedirect is the solution.
EDIT: Source - http://docs.oracle.com/javaee/1.3/api/javax/servlet/http/HttpServletResponse.html#sendRedirect(java.lang.String)
I need to put in my android applicazion a tool that uses the free service for sending free sms through internet...
I saw that many apps are able to integrate these sevices..
I tried a lot but I have not found anything useful..
So I ask you ... how can I use the gateway of uthsms.net (for example) for send SMS with my Android application?
Sorry for the generic question..but I not found any starting point for resolve this question.
Thanks in advance
Use a Tool like Firebug to see what gets sent when you click the button on the website. I see that a POST-Request is done to uthsms.net with some parameters. You should be able to do the same POST with your app.
These are the parameter:
button: Send SMS
country: (some integer)
gateway: 0
hyderabad: your message
remLen: remaining length??
sindh: number to send sms to (without the +)
x: some integer
y: some integer
To send this POST-request in Android use following code:
URL url = new URL("http://uthsms.net");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = URLEncoder.encode("button", "UTF-8") + "="
+ URLEncoder.encode("Send SMS", "UTF-8");
data += "&" + URLEncoder.encode("country", "UTF-8") + "="
+ URLEncoder.encode(country, "UTF-8");
data += "&" + URLEncoder.encode("gateway", "UTF-8") + "="
+ URLEncoder.encode("0", "UTF-8");
data += "&" + URLEncoder.encode("hyderabad", "UTF-8") + "="
+ URLEncoder.encode(message, "UTF-8");
data += "&" + URLEncoder.encode("remLen", "UTF-8") + "="
+ URLEncoder.encode(remLen, "UTF-8");
data += "&" + URLEncoder.encode("sindh", "UTF-8") + "="
+ URLEncoder.encode(number, "UTF-8");
data += "&" + URLEncoder.encode("x", "UTF-8") + "="
+ URLEncoder.encode("0", "UTF-8");
data += "&" + URLEncoder.encode("y", "UTF-8") + "="
+ URLEncoder.encode("0", "UTF-8");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader inStream = new BufferedReader(new InputStreamReader((conn.getInputStream())));
result = inStream.readLine();
inStream.close();
The result seems to be a html-document. Somewhere inside you should find the success message, or possible errors.
Try GoogleVoice API. It has documentation, which might help you get started.
Here's a link : https://code.google.com/p/google-voice-java/