我基本上是从Android上传图像并上传到PHP服务器,但在这里我没有得到任何与此代码或图像上传的连接.
我收到了这个错误.
Error in http connection java.net.UnknownHostException: host name
但据我所知,我给了正确的连接和PHP文件也在正确的域.
看看我的代码:
UploadImage.java
public class UploadImage extends Activity {
InputStream inputStream;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,90,stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayListPHP");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(UploadImage.this,"Response " + the_string_response,Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(UploadImage.this,"ERROR " + e.getMessage(),Toast.LENGTH_LONG).show();
System.out.println("Error in http connection "+e.toString());
}
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException,IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
Toast.makeText(UploadImage.this,"contentLength : " + contentLength,Toast.LENGTH_LONG).show();
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data,len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
Toast.makeText(UploadImage.this,"Result : " + res,Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}
PHP
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg','wb');
fwrite($file,$binary);
fclose($file);
echo 'Image upload complete!!,Please check your PHP file directory……';?>
最佳答案
问题很明显……
原文链接:https://www.f2er.com/mysql/433754.htmlError in http connection java.net.UnknownHostException: host name
表示HttpPost无法使用您提供的主机名建立连接 – 因为您提供的主机名是未知的.
如果您从此行获取主机名:
HttpPost httppost = new HttpPost("http://server.com/uploadimage/uploadimage.PHP");
并将其放在同一设备上的浏览器中会发生什么……我建议您收到错误消息,说无法连接到主机.如果这样可行,那么我建议您检查以下行是否在您的清单中:
header('Content-Type: image/jpg');