localhost is not working, I am using a SQL Server database now, but I don't know what to put in localhost IP, I tried 10.0.2.2 and my ipv4 ip. it doesn't work too.
HttpClient client = new HttpClient();
string url = $"https://localhost:xxxxx/api/Feedback?email={feedback.Email}&subject={feedback.Subject}&message={feedback.Message}";
Exception
System.Net.WebException: 'Failed to connect to localhost/127.0.0.1:44330'
Code:
btnSend.Click += async delegate
{
Feedback feedback = new Feedback();
feedback.Email = edtEmail.Text;
feedback.Subject = edtSubject.Text;
feedback.Message = edtMessage.Text;
HttpClient client = new HttpClient();
string url = $"https://localhost:xxxxxx/api/Feedback?email={feedback.Email}&subject={feedback.Subject}&message={feedback.Message}";
var uri = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
var json = JsonConvert.SerializeObject(feedback);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await client.PostAsync(uri, content);
Clear();
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
Toast.MakeText(this, "Your Feedback is Saved ", ToastLength.Long).Show();
}
else
{
Toast.MakeText(this, "Your Feedback is not Saved", ToastLength.Long).Show();
}
};
}
Image of WebAPI:
Contents of WebAPI
It Depends on your Dev environment setup, if you are using a real phone then you have to make sure that your PC and your phone are on the same network and the corresponding port number is open in your PC firewall elsewhere the phone can't reach the service.
I am working on android for the first time, I just want to connect my android app with node server on a button click. my node server is
running on localhost and my mobile is also connected to the same
network. can it be possible to connect my android app with running
node server. what i have to do to call a route of server that only
prints "Hello world" in console.log of server.
If possible please help me with the code.
Thanks.
**This is my ooClick function in android.**
public void sendMessage(View view) {
name = (EditText)findViewById(R.id.name);
email = (EditText)findViewById(R.id.email);
phone = (EditText)findViewById(R.id.phone);
address = (EditText)findViewById(R.id.address);
try {
String nme = URLEncoder.encode(name.getText().toString(), "UTF-8");
String eMail = URLEncoder.encode(email.getText().toString(), "UTF-8");
String ph = URLEncoder.encode(phone.getText().toString(), "UTF-8");
String add = URLEncoder.encode(address.getText().toString(), "UTF-8");
// Create http client object to send request to server
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "http://192.168.0.183:3000/save?text1="+nme+"&text2="+eMail+"&text3="+ph+"&text4="+add;
//Toast.makeText(getBaseContext(),"Please wait, connecting to server."+URL,Toast.LENGTH_LONG).show();
try
{
String SetServerString = "";
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
// Show response on activity
//content.setText(SetServerString);
Toast.makeText(getBaseContext(),"response"+SetServerString,Toast.LENGTH_LONG).show();
}
catch(Exception ex)
{
Toast.makeText(getBaseContext(),"fail",Toast.LENGTH_LONG).show();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(),"response",Toast.LENGTH_LONG).show();
}
**This is my function in node server**
app.get('/save', function(req, res){
var text1= req.param('text1');
var text2= req.param('text2');
var text3= req.param('text3');
var text4= req.param('text4');
console.log(text1+' '+text2+' '+text3);
});
I just want to print the texts in console.
You should look into using the Retrofit library. This makes it very easy to make HTTP calls from and Android app. Also, you will need the external IP address or server name in order to access the data over your network. "localhost" always refers to the current machine where the software is running. For your desktop, "localhost" is the desktop; for your Android device, "localhost" is the Android device.
Iam sending a POST request from my android app using Xamarin. Iam using HttpClient to make the request
Things I have done:
1) Specified Internet permission
2) Tested the request from Postman for google Chrome
3) Debugged the code step by step
Problem:
1) I get the response as null.
2) Found the issue might be while receiving the response.
Here is my code:-
var resultString = String.Empty;
var registerContent = new StringBuilder();
registerContent.Append("DeviceId=");
registerContent.Append(deviceId);
registerContent.Append("&");
registerContent.Append("Name=");
registerContent.Append(deviceName);
registerContent.Append("&");
registerContent.Append("EncodedAccountNameā€¸=");
registerContent.Append(username);
var client = DataClient.Instance;
var request = new HttpRequestMessage(HttpMethod.Post,new Uri(EndPoints.RegisterDeviceEndPoint, UriKind.Absolute))
{
Content = new StringContent("DeviceId=" + deviceId + "&Name=" + deviceName + "&EncodedAccountName=" + username)
};
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var result = await client.SendAsync(request);
if (result.StatusCode == HttpStatusCode.OK)
{
resultString = HostUrl.GeAuthorizationtResult(result.Content.ReadAsStringAsync().Result);
}
return resultString;
Any help is appreciated
Thanks
It looks like you have a lot of app-specific code in there, so it's difficult to say what's causing the issue. You can simplify your code by using HttpClient's built-in support for form posts.
var httpClient = new HttpClient();
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("DeviceId", deviceId),
new KeyValuePair<string, string>("Name", deviceName),
new KeyValuePair<string, string>("EncodedAccountName", username)
};
var response = await httpClient.PostAsync(requestUrl, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
var resultString = await response.Content.ReadAsStringAsync();
Try this and see if it solves the issue. Otherwise, you'll need to expand on what HostUrl.GeAuthorizationtResult() does.
Is there a way to send android local HTML forms via ajax to remote php server? (local means the files are in my device) My scenario is this: In my app, I have an html files in my android device and is loaded in a webview, i also have the javascript file in my device. What i want to do is to send the html forms data to a remote server. In my current situation, its not sending any data, I've check the javascript and php and the code is fine, and it's working on iOS version of the app. I've tried other workarounds and what I've observed is that, when i load html file in webview using local files (e.g. webview.loadUrl("file://"+ Environment.getExternalStorageDirectory()+"/android_asset/list.html"), the android is looking for all other related files (e.g. formsprocessor.php) locally, though in javascript/ajax all necessary arguments in it's functions are supplied properly. The errors i've encountered are: FileNotFound: content://packagename.com/formsprocessor.php & Unknown chronium error: -6.
Is there a way or what is the best way to do this?
Thanks, Clint.
This solve my problem:
Used a javascripthandler, and in my javascript i call the function from the handler. So basically, the android handled the upload of data to server using httppost. Here's the codes;
the handler:
final class IJavascriptHandler{
IJavascriptHandler(){}
public void sendJSONToAndroid(String text){
if(!Config.canConnect((ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE), home) && dialogNoConnFlag == false) {
dialogNoConnFlag = true;
Config.notificationMsg(Config.ERRORNOCONN,home, Config.TITLE1 + " " + Config.TITLE6);
return;
}
try {
Log.v("SendToServer","Send JSON to Server");
String url = "";
JSONObject json_data = new JSONObject(text);
JSONArray names= json_data.names();
JSONArray values = json_data.toJSONArray(names);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for(int i = 0 ; i < values.length(); i++){
Log.v("Good",names.getString(i).toString());
if(names.getString(i).equals("url")) {
url = json_data.getString(names.getString(i)).toString();
}
nameValuePairs.add(new BasicNameValuePair( names.getString(i).toString(), json_data.getString(names.getString(i)).toString()));
}
Config.uploadToServer(nameValuePairs, url);
}
catch (JSONException e)
{
Config.notificationMsg(Config.ERRORMSG + e.getMessage(), (Activity) home, Config.TITLE1 + " " + Config.TITLE6);
}
}
}
the httppost:
public static String uploadToServer(List<NameValuePair> nameValuePairs, String url){
if(Session.isordinaryHost)
{
httpclient = new DefaultHttpClient();
}
else
{
httpclient = new MyHttpClient().getNewHttpClient();
((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(
new AuthScope(Session.siteIp, 443),
new UsernamePasswordCredentials(Session.siteUsername, Session.sitePassword));
}
httppost = new HttpPost(url);
try
{
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
EntityUtils.toString(entity);
}
catch (ClientProtocolException e)
{
return e.getMessage();
}
catch (IOException e)
{
return e.getMessage();
}
return null;
}
the javascript:
function CheckCompleteRecords() {
DB.transaction(function(tx) {
tx.executeSql(SelectCompleteForUploadStatement, [], function(tx, result) {
Dataset = result.rows;
for (var i = 0, item = null; i < Dataset.length; i++) {
item = Dataset.item(i);
var a = createJSON(item['FormName'],item['UserID'],item['Image1'],item['Image2'],item['Image3'],item['Image4'],item['Image5'],item['Field1'],item['Field2'],item['Field3'],item['Field4'],item['Field5'],item['Field6'],item['Field7'],item['Field8'],item['Field9'],item['Field10'],item['Field11'],item['Field12'],item['Field13'],item['Field14'],item['Field15'],item['Field16'],item['Field17'],item['Field18'],item['Field19'],item['Field20'],item['Field21'],item['Field22'],item['Field23'],item['Field24'],item['Field25'],item['Field26'],item['Field27'],item['Field28'],item['Field29'],item['Field30'],item['Field31'],item['Field32'],item['Field33'],item['Field34'],item['Field35'],item['Field36'],item['Field37'],item['Field38'],item['Field39'],item['Field40'],item['Field41'],item['Field42'],item['Field43'],item['Field44'],item['Field45'],item['Field46'],item['Field47'],item['Field48'],item['Field49'],item['Field50'],item['Field51'],item['Field52'],item['Field53'],item['Field54'],item['Field55'],item['Field56'],item['Field57'],item['Field58'],item['Field59'],item['Field60'],item['Field61'],item['Field62'],item['Field63'],item['Field64'],item['Field65'],item['Field66'],item['Field67'],item['Field68'],item['Field69'],item['Field70'],item['Field71'],item['Field72'],item['Field73'],item['Field74'],item['Field75'],item['Field76'],item['Field77'],item['Field78'],item['Field79'],item['Field80'],item['Field81'],item['Field82'],item['Field83'],item['Field84'],item['Field85'],item['Field86'],item['Field87'],item['Field88'],item['Field89'],item['Field90'],item['Field91'],item['Field92'],item['Field93'],item['Field94'],item['Field95'],item['Field96'],item['Field97'],item['Field98'],item['Field99'],item['Field100'],item['CurrentDateTime'],item['Geolocation'],item['BarCode']);
window.cpjs.sendJSONToAndroid(a);
showStuff('SendServerBtn');
window.location = "senttoserver://app_action";
}
});
});
}
I have a rest webservice that takes a POST metod with multipart message:
#Path("transferFile")
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_XML)
public String multipartTest(com.sun.jersey.multipart.MultiPart data) {
try {
// get first body part (index 0)
BodyPart bp = multiPart.getBodyParts().get(0);
etc..
Now I am trying to write a java client for that. I started with a simple jersey client:
view plaincopy to clipboardprint?
MultiPart multiPart = new MultiPart();
multiPart.bodyPart( new BodyPart(wavestream,MediaType.APPLICATION_OCTET_STREAM_TYPE));
Client c = Client.create();
WebResource r = c.resource("http://127.0.0.1:8080/webapp:);
response=r.path("transferFile").type(MediaType.MULTIPART_FORM_DATA).accept(MediaType.APPLICATION_XML).post(String.class, multiPart);
This works great - everything is ok. However I need this client working on Android and I have trouble with using jersey on that platform. So I used the normal way to send multipart message on android:
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter("http.socket.timeout", new Integer(90000)); // 90 second
HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/webapp/transferFile");
httpPost.setHeader("Content-Type", MediaType.MULTIPART_FORM_DATA );
//tried with and without base64
byte [] encodedWavestream = Base64.encodeBytesToBytes(wavestream);
InputStream ins = new ByteArrayInputStream(encodedWavestream);
InputStreamBody body = new InputStreamBody(ins, "test" );
int send = ins.available();
MultipartEntity requestContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE );
requestContent.addPart("stream", body);
httpPost.setEntity(requestContent);
HttpResponse Response = client.execute(httpPost);
An this gives an annoying response from the server :
HTTP Status 400 - Bad Request
The request sent by the client was syntactically incorrect (Bad Request).
I check the server log files but there is nothing there. So I don't know what's the origin of this error. I have wrote a simple html page with a post formula and 'multipart/form-data' content-type and it also works! An auto-generated request from soapUI also works! Why my client does not work? Can anybody help?
There is bug in Jersey. See Chunked encoding problem.
This problem appears only for few clients (iOS, Android).
If you set the Content-Type to application/octet-stream, then the Jersey MessageWriter for the application/octet-stream will set the Content-Length and
not send as chunked transport method.
There is solution for Jersey Client:
ClientConfig config = new DefaultClientConfig();
config.getProperties().put(ClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE, 32 * 1024);
But it doesn't work for the iOS's or Android's client.
So I tested Apache File Upload. Threre was another bug: "Stream ended unexpectedly".
Only Oreilly upload can upload file correct for all clients.
This is my code:
public Object[] getParametersAndFiles(HttpServletRequest request) throws IOException {
log.debug("OreillyUpload");
Properties params = new Properties();
LinkedHashMap files = new LinkedHashMap();
File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
MultipartParser mp = new MultipartParser(request, 1*1024*1024); // 10MB
Part part;
while ((part = mp.readNextPart()) != null) {
String name = part.getName();
if (part.isParam()) {
// it's a parameter part
ParamPart paramPart = (ParamPart) part;
String value = paramPart.getStringValue();
params.put(name, value);
log.debug("param; name=" + name + ", value=" + value);
}
else if (part.isFile()) {
// it's a file part
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
if (fileName != null) {
// the part actually contained a file
File file = new File(tempDirectory,fileName);
long size = filePart.writeTo(file);
files.put(name, file);
log.debug("file; name=" + name + "; filename=" + fileName +
", filePath=" + filePart.getFilePath() +
", content type=" + filePart.getContentType() +
", size=" + size);
}
else {
// the field did not contain a file
log.debug("file; name=" + name + "; EMPTY");
}
}
}
return new Object[] {params, files};
}
And this is Jersey Server code (warning all Jersey Upload anotations (like as "#FormDataParam") should be removed):
#POST
#Path("uploadMarkup")
#Produces(MediaType.APPLICATION_JSON)
// #Consumes(MediaType.MULTIPART_FORM_DATA)
//// public void uploadMarkup(
// public JSONWithPadding uploadMarkup(
// #FormDataParam("markupFile") InputStream markupFile,
// #FormDataParam("markupFile") FormDataContentDisposition details,
// #FormDataParam("slideNum") int slideNum) {
public JSONWithPadding uploadMarkup(#Context HttpServletRequest request) {
Object[] data = uploadService.getParametersAndFiles(request);
...
}